import { Component, OnInit ,OnDestroy} from '@angular/core';
import { Router ,RouteParams} from '@angular/router-deprecated';
import { Param } from '../model/param.model';
import { Resp } from '../model/resp.model';
import { Api } from '../model/api.model';
import { Proj } from '../model/proj.model';
import { Group } from '../model/group.model';
import {BaseRequestOptions,Http,Response, HTTP_PROVIDERS,Headers} from '@angular/http';
import { GlobalService } from '../services/global.service';
import { BaseService } from '../services/base.service';
import { ApiService } from '../services/api.service';
import { GroupService } from '../services/group.service';
import { ProjService } from '../services/proj.service';

@Component({
  selector: 'api-component',
  viewProviders: [HTTP_PROVIDERS,ApiService,GroupService,ProjService],
  templateUrl: 'app/api/tpl/api.tpl.html'
})
export class ApiComponent implements OnInit,OnDestroy{
  apiData:Api = new Api();
  groups:Group[] = [];
  proj:Proj = new Proj();
  constructor(private router: Router,routeParams:RouteParams,private projService:ProjService,private groupService:GroupService,private apiService:ApiService) {
    this.apiData.resps = [];
    this.apiService.authInit(router,()=>{

      var projId = routeParams.get("projId");
      var groupId = routeParams.get("groupId");
      var apiId = routeParams.get("apiId");
      if(apiId)
      {
        this.apiService.get(apiId).subscribe(data=>{
          this.apiData = data.json();
        });
      }
      if(groupId)
      {
        this.apiData.groupId = groupId;
        alert(groupId)
      }
      if(projId)
      {
        this.groupService.getGroups(projId).subscribe(data=>this.groups =data.json());
        this.projService.getProj(projId).subscribe(data=>this.proj=data.json());
      }
    });

  }

  ngOnInit() {
    this.apiData.httpMethod = "GET";
  }

  ngOnDestroy(){

  }

  addParam() {
    var param = new Param();
    param.optional = 1;
    param.paramType = "String";
    param.paramStyle = "Query";
    this.apiData.params.push(param);
  }

  addResp(){
    var resp = new Resp();
    resp.respCode = "200";
    resp.respType = "JSON";
    this.apiData.resps.push(resp);
  }

  removeParam(i) {
    this.apiData.params.splice(i,1);
  }

  removeResp(i) {
    this.apiData.resps.splice(i,1);
  }
  submit()
  {
    if(this.apiData._id)
    {
      this.apiService.update(this.apiData).subscribe(data=>{
        this.router.navigate(['ShowApi',{apiId:this.apiData._id}])
      });
    }else
    {
      this.apiData.projectId = this.proj._id;
      this.apiService.add(this.apiData).subscribe(data=>{
        this.router.navigate(['ShowApi',{apiId:data.json()._id}])
      });

    }
  }


}

/*
Copyright 2016 Google Inc. All Rights Reserved.
Use of this source code is governed by an MIT-style license that
can be found in the LICENSE file at http://angular.io/license
*/
